<?php

/* Bootstrap */
require '../bootstrap.php';



while (true) {
    $db->beginTransaction();

    // Get next message from queue
    $select = $db->select()
        ->forUpdate()
        ->from('queue')
        ->where('status = 0')
        ->limit(1);
    $messages = $db->fetchAll($select);

    if ($messages) {

        foreach ($messages as $message) {

            // Execute engine
            $responseCode = Pexi_Engine::execute($message);

            // Status by response code
            if ($responseCode == 200) {

                // Delete message from queue
                $db->delete(
                    'queue',
                    'id = ' . $message['id']
                );

            } else {

                // Update queue status to error
                $status = 2;
                $db->update(
                    'queue',
                    array('status' => $status),
                    'id = ' . $message['id']
                );

            }

            // Log
            echo $message['id'] . ' - ' . $message['message'] . ' - ' . $responseCode . "\n";

        }

        try {
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            echo $e->getMessage();
        }

    } else {

        $db->commit();
        sleep(5);
    }


}